package com.hunau.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.hunau.common.core.domain.Ztree;
import com.hunau.common.exception.BusinessException;
import com.hunau.common.utils.StringUtils;
import com.hunau.system.domain.AddrTree;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hunau.system.mapper.TerminalsMapper;
import com.hunau.system.domain.Terminals;
import com.hunau.system.service.ITerminalsService;
import com.hunau.common.core.text.Convert;

/**
 * 终端管理（终端管理的主）Service业务层处理
 * 
 * @author ruoyi
 * @date 2020-03-15
 */
@Service
public class TerminalsServiceImpl implements ITerminalsService 
{
    private static final Logger log = LoggerFactory.getLogger(TerminalsServiceImpl.class);
    @Autowired
    private TerminalsMapper terminalsMapper;

    /**
     * 查询终端管理（终端管理的主）
     * 
     * @param tid 终端管理（终端管理的主）ID
     * @return 终端管理（终端管理的主）
     */
    @Override
    public Terminals selectTerminalsById(String tid)
    {
        return terminalsMapper.selectTerminalsById(tid);
    }

    /**
     * 查询终端管理（终端管理的主）列表
     * 
     * @param terminals 终端管理（终端管理的主）
     * @return 终端管理（终端管理的主）
     */
    @Override
    public List<Terminals> selectTerminalsList(Terminals terminals)
    {
        return terminalsMapper.selectTerminalsList(terminals);
    }

    @Override
    public List<Terminals> selectTerminalsListByIds(List<Object> array) {
        return terminalsMapper.selectTerminalsListByIds(array);
    }

    /**
     * 新增终端管理（终端管理的主）
     * 
     * @param terminals 终端管理（终端管理的主）
     * @return 结果
     */
    @Override
    public int insertTerminals(Terminals terminals)
    {
        return terminalsMapper.insertTerminals(terminals);
    }

    /**
     * 修改终端管理（终端管理的主）
     * 
     * @param terminals 终端管理（终端管理的主）
     * @return 结果
     */
    @Override
    public int updateTerminals(Terminals terminals)
    {
        return terminalsMapper.updateTerminals(terminals);
    }

    /**
     * 删除终端管理（终端管理的主）对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteTerminalsByIds(String ids)
    {
        return terminalsMapper.deleteTerminalsByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除终端管理（终端管理的主）信息
     * 
     * @param tid 终端管理（终端管理的主）ID
     * @return 结果
     */
    @Override
    public int deleteTerminalsById(String tid)
    {
        return terminalsMapper.deleteTerminalsById(tid);
    }
    @Override
    public String importUser(List<Terminals> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new BusinessException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (Terminals user : userList) {
            try {
                // 验证是否存在这个用户
                Terminals u = terminalsMapper.selectTerminalsByMid(user.getTid());
                System.out.println(u.toString());
                System.out.println(user.toString());
                if (StringUtils.isNull(u)) {
                    this.insertTerminals(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、MIM " + user.getTid() + " 导入成功");
                } else if (isUpdateSupport) {
                    this.updateTerminals(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、MIM " + user.getTid() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、MIM " + user.getTid() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、MIM " + user.getTid() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
    @Override
    public List<Ztree> selectAddrTree(AddrTree addr) {
        List<String> addrList = terminalsMapper.selectAddrList();
        List<Ztree> ztrees = initZtree(addrList);
        return ztrees;
    }
    /**
     * 对象转部门树
     *
     * @param addrList 部门列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<String> addrList)
    {
        return initZtree(addrList, null);
    }

    /**
     * 对象转部门树
     *
     * @param addrList 部门列表
     * @param roleAddrList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<String> addrList, List<String> roleAddrList)
    {

        List<Ztree> ztrees = new ArrayList<Ztree>();
        long i = 1;
        Ztree ztree1 = new Ztree();
        ztree1.setId((long)0);
        ztree1.setpId((long)0);
        ztree1.setName("湖南");
        ztree1.setTitle("");
        ztrees.add(ztree1);
        for (String addr : addrList)
        {
            String[] list = addr.split("/");
            if(list.length>1){
                String old = "";
                int tag = 0;
                long oldId = 0;
                for (String ll:list) {
                    Ztree ztree = new Ztree();
                    if (tag == 0){
                        ztree.setId(i);
                        ztree.setpId((long)0);
                        ztree.setName(ll);
                        ztree.setTitle("湖南");
                        Ztree ztree2 = check(ztrees,ztree);
                        if(ztree2==null){
                            ztrees.add(ztree);
                            old = ll;
                            tag ++;
                            oldId = i;
                        }else {
                            old = ztree2.getName();
                            oldId = ztree2.getId();
                            tag++;
                        }
                    }else {
                        ztree.setId(i);
                        ztree.setpId(oldId);
                        ztree.setName(ll);
                        ztree.setTitle(old);
                        ztrees.add(ztree);
                        Ztree ztree2 = check2(ztrees,ztree);
                        if(ztree2==null){
                            old = ll;
                            oldId = i;
                            ztrees.add(ztree);
                        }else {
                            old = ztree2.getName();
                            oldId = ztree2.getId();
                            tag++;
                        }
                    }
                    i++;
                }
            }else {
                Ztree ztree = new Ztree();
                ztree.setId(i);
                ztree.setpId((long) 0);
                ztree.setName(addr);
                ztree.setTitle("湖南");
                ztrees.add(ztree);
                i++;
            }
        }
        return ztrees;
    }
    public Ztree check( List<Ztree> ztrees,Ztree ztree){
        for (Ztree z:ztrees ) {
            if (z.getName().equals(ztree.getName())){
                return z;
            }
        }
        return null;
    }
    public Ztree check2( List<Ztree> ztrees,Ztree ztree){
        for (Ztree z:ztrees ) {
            if (z.getName().equals(ztree.getName())&& z.getpId().equals(ztree.getpId())){
                return z;
            }
        }
        return null;
    }
}
